<?php
/**
 * 用户业务类
 */
class core_service_user extends core_service {
	protected $id;
	protected $marter_table = 'core_model_user';

	/**
	 * 实例化对象
	 * @param int $id
	 */
	public function __construct($id = 0) {
		parent::__construct();
		$this->id = $id;
	}
	
	/**
	 * 注册
	 */
	function register($username, $userpwd, $email=''){
		if(!$username){
			$this->setError(0,'缺少参数');
			return false;
		}
		if(strlen($username) >= 30){
			$this->setError(0,'用户名不能超过30个字符');
			return false;
		}
		if(!$userpwd){
			$userpwd = Qutil::getRandom(8);
			$notice = 1;
		}
		$condi = array('username'=>$username);
		if($email) $condi['email'] = $email;
		if($this->model()->selectOne($condi)){
			$this->setError(0,'用户名或者邮箱已经被注册');
			return false;
		}
		$this->set('username', $username);
		$this->set('userpwd', $this->createPwd($userpwd));
		$this->set('email', $email);
		$this->set('reg_ip', Qutil::getIP());
		$this->set('reg_time', $this->_time);
		$this->set('login_ip', Qutil::getIP());
		$this->set('login_time', $this->_time);
		if($this->save() === false){
			$this->setError(0,'注册发生错误。');
			return false;
		}
		$uid = $this->getLastId();
		$this->setId($uid);
		$this->setLogin();
		return $uid;
	}
	
	/**
	 * 登录
	 */
	function login($username, $userpwd=''){
		$rs = $this->model()->selectOne(array('username'=>$username));
		if($rs['uid']){
			$this->id = $rs['uid'];
			if($this->get('locks') == 1){
				if($rs['locktime'] >0 && $this->_time>$rs['locktime']){
					$this->unLocks();
				}else{
					$this->setError(0,'帐号被锁定');
					return false;
				}
			}
			if($userpwd && $this->createPwd($userpwd) != $rs['userpwd']){
				$this->setError(0,'用户名或者密码错误');
				return false;
			}
		}else{
			$this->setError(0,'用户名或者密码错误');
			return false;
		}
		$this->setId($rs['uid']);
		$this->setLogin();
		return true;
	}
	
	/**
	 * 修改密码
	 */
	function changePassword($newpwd, $oldpwd=''){
		if(!$this->id) return false;
		if(!$newpwd){
			$this->setError(0,'密码不能为空');
			return false;
		}
		if($oldpwd && $this->createPwd($oldpwd) != $this->get('userpwd')){
			$this->setError(0,'原密码错误');
			return false;
		}
		$this->set('userpwd', $this->createPwd($newpwd));
		return $this->save();
	}
	
	/**
	 * 锁定用户
	 */
	function locks($day=0){
		if(!$this->id) return false;
		$this->set('lock',1);
		if($day>0){
			$this->set('locktime',$this->_time+intval($day)*86400);
		}
		return $this->save();
	}
	
	/**
	 * 锁定用户
	 */
	function unLocks(){
		if(!$this->id) return false;
		$this->set('lock',0);
		$this->set('locktime',0);
		return $this->save();
	}
	
	/**
	 * 编辑资料
	 */
	function edit($data = array()){
		if(!$this->id) return false;
		if($data['email']) $this->set('email', $data['email']);
		if($data['qq']) $this->set('qq', $data['qq']);
		if($data['phone']) $this->set('phone', $data['phone']);
		if($data['zip']) $this->set('zip', $data['zip']);
		if($data['intro']) $this->set('intro', $data['intro']);
		if($data['team']) $this->set('team', $data['team']);
		if($data['homeurl']) $this->set('homeurl', $data['homeurl']);
		if($data['address']) $this->set('address', $data['address']);
		if($data['realname']) $this->set('realname', $data['realname']);
		if($this->save() === false){
			$this->setError(0,'编辑资料出错');
			return false;
		}
		return true;
	}
	
	/**
	 * 退出登录
	 */
	function logout(){
		$cookie = array('uid'=>0,'t'=>0,'name'=>'','skey'=>'');
		Qutil::ssetcookie($cookie, -1);
	}
	
	/**
	 * 设置登录状态
	 */
	function setLogin($time = 86400){
		if(!$this->id) return false;
		$cookie = array(
			'uid'=>Qutil::enId($this->id),
			't'=>$this->_time,
			'name'=>$this->get('username'),
			'skey'=>md5($this->id.$this->get('username').$this->_time.core_lib_constant::COOKIE_KEY),
		);
		Qutil::ssetcookie($cookie, $time);
		$this->set('login_ip', Qutil::getIP());
		$this->set('login_time', $this->_time);
		$this->save();
		$this->getUserNewNoticeNum();
	}
	
	/**
	 * 检查是否登录
	 */
	function isLogin(){
		if($_COOKIE['skey'] && $_COOKIE['skey'] == md5(Qutil::deId($_COOKIE['uid']).$_COOKIE['name'].$_COOKIE['t'].core_lib_constant::COOKIE_KEY)){
			return true;
		}
		$this->logout();
		return false;
	}
	
	/**
	 * 创建通知
	 */
	function addNotice($type, $content, $f_userid=0){
		if(!$this->id or !$type or !$content){
			$this->setError(0, '缺少参数');
			return false;
		}
		$data = array(
			'notice.user_id'=>$this->id,
			'notice.f_user_id'=>$f_userid,
			'notice.type'=>intval($type),
			'notice.create_time'=>$this->_time,
			'notice.ip'=>Qutil::getIP(),
			'notice.content'=>$content
		);
		foreach ($data as $k=>$v){
			$this->set($k, $v);
		}
		return $this->save();
	}
	
	/**
	 * 标记为已读(删除)
	 */
	function readNotice($nid, $is_del = 0){
		if(!$this->id) return false;
		$model = new core_model_notice($nid);
		if($this->id == $model->getData('user_id') && $model->getData('is_del') == 0){
			$model->set('is_read', 1);
			if($is_del == 1) $model->set('is_del', 1);
			$model->save();
			$this->getUserNewNoticeNum();
			return true;
		}
		return false;
	}
	

	/**
	 * 兑换礼品
	 * @param object $user
	 */
	function exchange($gid, $consignee = array()){
		if(!$this->id) return false;
		if(!$consignee['address'] or !$consignee['phone']){
			$this->setError(0, '收货信息不完善');
			return false;
		}
		try{
			$this->_beginTransaction();
			$this->setLock();
			$gift = new core_model_gift($gid);
			if($gift->getData('stock') <= 0){
				$this->setError(0, '暂时缺货');
				return false;
			}
			if($this->get('rank') < $gift->getData('rank')){
				$this->setError(0, '您的'.core_lib_constant::UNIT.'不足。');
				return false;
			}
			$model = new core_model_order();
			$order = array(
				'realname'=>$consignee['realname'],
				'address'=>$consignee['address'],
				'zip'=>$consignee['zip'] ? $consignee['zip'] :0,
				'phone'=>$consignee['phone'],
				'rank'=>$gift->getData('rank'),
				'create_time'=>$this->_time,
				'gift_id'=>$gift->getData('gid'),
				'gift_name'=>$gift->getData('gift_name'),
				'user_id'=>$this->get('user_id')
			);
			if($model->insert($order) === false){
				throw new Exception("保存订单出错。");
			}
			$gift->set('stock', $gift->getData('stock')-1);
			$gift->set('sales', $gift->getData('sales')+1);
			if($gift->save() === false){
				throw new Exception("保存礼物数据出错。");
			}
			$this->set('rank', $this->get('rank')-$gift->get('rank'));
			if($this->save() === false){
				throw new Exception("保存用户信息出错");
			}
			$this->_commit();
			return true;
		} catch (Exception $e) {
			$this->setError(0,$e->getMessage());
			$this->_rollBack();
			return false;
		}
	}
	
	/**
	 * 取消兑换
	 */
	function cancelExchange($oid){
		if(!$this->id) return false;
		try{
			$this->_beginTransaction();
			$this->setLock();
			$model = new core_model_order($oid);
			if($model->getData('is_send') == 1){
				throw new Exception("已经发货，不能取消");
			}
			if($model->getData('user_id') != $this->id){
				throw new Exception("参数错误");
			}
			$model->set('cancel', 1);
			$model->set('cancel_time', $this->_time);
			if($model->save() === false){
				throw new Exception("保存订单信息出错");
			}
			$gift = new core_model_gift($model->getData('gift_id'));
			$gift->set('stock', $gift->getData('stock')+1);
			$gift->set('sales', $gift->getData('sales')-1);
			if($gift->save() === false){
				throw new Exception("保存礼物数据出错。");
			}
			$this->set('rank', $this->get('rank')+$model->getData('rank'));
			if($this->save() === false){
				throw new Exception("保存用户信息出错");
			}
			$this->_commit();
			return true;
		} catch (Exception $e) {
			$this->setError(0,$e->getMessage());
			$this->_rollBack();
			return false;
		}
	}
	
	/**
	 * 发货
	 */
	function sendGift($oid){
		$model = new core_model_order($oid);
		if($model->getData('is_send') == 1){
			$this->setError(0, '已经发货，不能取消');
			return false;
		}
		if($model->getData('cancel') == 1){
			$this->setError(0, '已经取消，不能发货');
			return false;
		}
		if($model->getData('user_id') != $this->id){
			$this->setError(0, '参数错误');
			return false;
		}
		$model->set('is_send', 1);
		$model->set('send_time', $this->_time);
		return $model->save();
	}
	
	/**
	 * 生成密码
	 * @param unknown_type $pwd
	 */
	private function createPwd($pwd){
		return md5(md5($pwd));
	}
	
	function getUserNewNoticeNum(){
		$notice = new core_model_notice();
		$rs = $notice->selectOne(array('user_id'=>$this->id,'is_read'=>0),'count(1) as num');
		Qutil::ssetcookie(array('_notice'=>$rs['num']));
	}
}